﻿using Microsoft.Extensions.Logging;
using SKIT.FlurlHttpClient.Wechat.Api;

namespace AiQiuQuan.Sport.Core.WechatApi
{
    /// <summary>
    /// WechatApiHttpClientFactory
    /// </summary>
    public interface IWechatApiHttpClientFactory
    {
        /// <summary>
        /// WechatApiClient
        /// </summary>
        /// <param name="appId">appId</param>
        /// <param name="secret">secret</param>
        WechatApiClient Create(string appId, string secret);
    }

    /// <summary>
    /// WechatApiHttpClientFactory
    /// </summary>
    public class WechatApiHttpClientFactory : IWechatApiHttpClientFactory
    {
        public readonly IHttpClientFactory _httpClientFactory;
        private readonly ILoggerFactory _loggerFactory;

        /// <summary>
        /// ctor
        /// </summary>
        public WechatApiHttpClientFactory(
            IHttpClientFactory httpClientFactory,
            ILoggerFactory loggerFactory)
        {
            _httpClientFactory = httpClientFactory;
            _loggerFactory = loggerFactory;
        }

        /// <summary>
        /// WechatApiClient
        /// </summary>
        /// <param name="appId">appId</param>
        /// <param name="secret">secret</param>
        public WechatApiClient Create(string appId, string secret)
        {
            var wechatApiClientOptions = new WechatApiClientOptions()
            {
                AppId = appId,
                AppSecret = secret,
            };
            var wechatApiClient = new WechatApiClient(wechatApiClientOptions);
            wechatApiClient.Interceptors.Add(new FlurlHttpLoggingInterceptor(_loggerFactory.CreateLogger("wechat")));
            wechatApiClient.Configure((settings) => settings.FlurlHttpClientFactory = new DelegatingFlurlClientFactory(_httpClientFactory));
            return wechatApiClient;
        }
    }

    /// <summary>
    /// DelegatingFlurlClientFactory
    /// </summary>
    internal class DelegatingFlurlClientFactory : Flurl.Http.Configuration.DefaultHttpClientFactory
    {
        private readonly IHttpClientFactory _httpClientFactory;

        public DelegatingFlurlClientFactory(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
        }

        public override HttpClient CreateHttpClient(HttpMessageHandler handler)
        {
            return _httpClientFactory.CreateClient();
        }
    }
}
